package com.g.localmsg.starter.config;

import com.g.localmsg.starter.service.TransactionService;
import com.g.localmsg.starter.task.TxRetryTask;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@ConditionalOnProperty(prefix = "ldtx", name = "enabled", havingValue = "true",matchIfMissing = true)
@EnableConfigurationProperties(DistributedTransactionProperties.class)
@ComponentScan(basePackages = "com.g.localmsg.starter")
@EnableScheduling
@MapperScan("com.g.localmsg.starter.mapper")
@EnableAspectJAutoProxy(exposeProxy = true, proxyTargetClass = true)
public class DistributedTransactionConfiguration {

    private static final Logger log = LoggerFactory.getLogger(DistributedTransactionConfiguration.class);

    @Autowired
    private DistributedTransactionProperties properties;

    /** 创建事务处理线程池 */
    @Bean
    public ThreadPoolExecutor transactionExecutor() {
        log.info("分布式事务处理线程池创建");
        return new ThreadPoolExecutor(properties.getThreadPool().getCorePoolSize(),
                properties.getThreadPool().getMaxPoolSize(), properties.getThreadPool().getKeepAliveSeconds(),
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(properties.getThreadPool().getQueueCapacity()),
                new CustomizedThreadFactory(properties.getThreadPool().getThreadNamePrefix()),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Bean
    @ConditionalOnProperty(prefix = "ldtx.retry", name = "enable-retry", havingValue = "true", matchIfMissing = true)
    public TxRetryTask txRetryTask(TransactionService transactionService) {
        log.info("注册分布式事务重试任务，扫描间隔: {}ms, 批次大小: {}", properties.getRetry().getScanInterval(),
                properties.getRetry().getBatchSize());
        return new TxRetryTask(transactionService, properties);
    }
}
